package cn.tedu.boot.demo.security;

import cn.tedu.boot.demo.mapper.AdminMapper;
import cn.tedu.boot.demo.vo.AdminLoginVO;
import cn.tedu.boot.demo.vo.PermissionSimpleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("尝试登陆,用户名={}",s);
        AdminLoginVO admin = adminMapper.getLoginInfoByUsername(s);
        if (admin == null) {
            log.debug("用户名为空");
            throw new BadCredentialsException("登陆失败,用户名不存在!");
        }

        List<PermissionSimpleVO> permissions = admin.getPermissions();
        log.debug("此用户的权限信息为:{}",permissions);
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (PermissionSimpleVO permission : permissions) {
            String permissionValue = permission.getValue();
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permissionValue);
            authorities.add(authority);
        }


        return User.builder()
                .username(admin.getUsername())
                .password(admin.getPassword())
                .disabled(admin.getIsEnable() == 0)
                .accountExpired(false)
                .accountLocked(false)
                .authorities(authorities)
                .build();


    }
}
